/*
 * @Author: lbt666 '1319451895@qq.com'
 * @Date: 2022-07-26 13:55:44
 * @LastEditors: lbt666 1319451895@qq.com
 * @LastEditTime: 2023-05-12 18:24:26
 * @Description: 实例化合约,获取余额,获取授权余额
 */
import {
  mainContractAddress,
  mianABi,
  TokenAddress,
  erc20Api,
  NftAddres,
  neverFailTokenAbi
} from '@/utils/casinoContract'
import { newBlockchainConnection } from '@/utils/getWeb'
import web3 from 'web3'
import contractStore from '@/store/modules/contract'
import * as BigToSmall from "@/utils/BNUtils.js";
import { KeepDecimal } from "@/utils/filter";


let WEB: any = ''
let userStore: any = ''
let contractInstance: any = ''
let address = ''
let Pair: any = ''
let nft: any = ''
let token: any = ''
let gk: any = ''

function init() {
  window.onload = async () => {
    WEB = newBlockchainConnection(web3.givenProvider || window.ethereum as any)
    userStore = contractStore()
    await userStore.SET_WEB3(WEB)
    await content()
    await queryBalance()
  }
}
async function content() {
  await WEB.eth.requestAccounts().then(async (res: string[], err: any) => {
    if (!err) {
      userStore.SET_Address(res[0])
      address = res[0]
      localStorage.setItem('address', address)
      // 实例化主合约
      contractInstance = new WEB.eth.Contract(
        mianABi,
        mainContractAddress
      )
      userStore.SET_Contract(contractInstance)
      // 实例化USDT合约
      token = new WEB.eth.Contract(
        erc20Api,
        TokenAddress
      )
      userStore.SET_ContractUSDT(token)
      // 实例化NFT合约
      nft = new WEB.eth.Contract(
        neverFailTokenAbi,
        NftAddres
      )
      userStore.SET_ContractNFT(nft)
    }
  })
}
async function queryBalance() {
  try {
    let usdts = await token.methods.balanceOf(address).call()
    let usdtRes = Number(BigToSmall.chufa(usdts, 18))
    userStore.SET_BalanceFrm(usdtRes)
    
    let gks = await nft.methods.balanceOf(address, 0).call()
    let gkRes = Number(gks)
    userStore.SET_BalanceNFT(gkRes)
  
    // 查询授权金额
    let quantityFrm = await token.methods.allowance(address, mainContractAddress).call()
    let allowanceFrm = Number(BigToSmall.chufa(quantityFrm, 18))
    let quantityNFT = await nft.methods.isApprovedForAll(address, mainContractAddress).call()
    console.log('授权', allowanceFrm, quantityNFT)
    userStore.SET_empowerFRM(allowanceFrm)
    userStore.SET_empowerNFT(quantityNFT)
  }catch(err) {
    console.log(err)
  }

}
init()